import { useState, useEffect, useRef, useMemo } from 'react';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
import './VideoPlayer.css';
import type Player from 'video.js/dist/types/player';
import axios from 'axios';
const VideoPlayer = ({ videoSrc, poster }: { videoSrc: string, poster?: string }) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const playerRef = useRef<Player>(null);
  const [isComponentMounted, setIsComponentMounted] = useState(false);  // 跟踪组件是否已挂载
  const [isPlayerReady, setIsPlayerReady] = useState(false);   // 跟踪播放器是否准备就绪

  const [originalPlaybackRate, setOriginalPlaybackRate] = useState(1);
  const [isLongPress, setIsLongPress] = useState(false);
  const longPressTimer = useRef<number | null>(null);
  const lastTimeRef = useRef<number>(0);

  const playbackRates = useMemo(() => { return [0.5, 0.75, 1, 1.25, 1.5, 2] }, []);
  // const volumeSteps = [0, 0.25, 0.5, 0.75, 1];

  useEffect(() => {
    setIsComponentMounted(true);  // 初始时确保组件已挂载

    return () => {
      setIsComponentMounted(false); // 组件卸载时取消挂载状态
    };
  }, []);

  useEffect(() => {
    if (!isComponentMounted) return;

    const videoElement = videoRef.current;
    if (!videoElement) return;

    const player = videojs(videoElement, {
      controls: true,
      fluid: true,
      responsive: true,
      preload: 'auto',
      sources: [{
        src: videoSrc,
        type: 'application/x-mpegURL'
      }],
      poster: poster,
      playbackRates: playbackRates,
      liveui: true,
      enableSmoothSeeking: true,
      controlBar: {
        skipButtons: {
          forward: 5,
          backward: 5
        }
      },
      html5: {
        hls: {
          overrideNative: true
        },
        nativeVideoTracks: false,
        nativeAudioTracks: false,
        nativeTextTracks: false
      }
    });

    playerRef.current = player;

    setIsPlayerReady(true);

    return () => {
      if (player) {
        player.dispose();
      }
    };
  }, [isComponentMounted, poster, videoSrc, playbackRates]);

  useEffect(() => {
    if (!isPlayerReady) return;

    const player = playerRef.current;
    if (!player) return;

    const onTimeUpdate = () => {
      const currentTime = player.currentTime() ?? 0;
      const previousTime = lastTimeRef.current;

      // // 检查是否为快进/快退等导致的跳跃（变化大于1秒）
      // if (Math.abs(currentTime - previousTime) > 1) {
      //   console.log(`进度跳转: 从 ${previousTime.toFixed(2)}s 到 ${currentTime.toFixed(2)}s`);
      // }
      // // 检查正常播放时是否跨过了整数秒
      // else if (Math.floor(currentTime) > Math.floor(previousTime)) {
      //   console.log(`播放进度: ${Math.floor(currentTime)}s`);
      // }
      // if (Math.abs(currentTime - previousTime) > 0.5)
      //   console.info(`播放进度: ${currentTime.toFixed(2)}s`);
      
      if (Math.abs(currentTime - previousTime) > 5) {
        console.info(currentTime, previousTime);
        axios.post('/api/playback/upload', { video_id: '7oCt4OtE7V', progress: currentTime })
        lastTimeRef.current = currentTime;
      }
    };

    player.on('timeupdate', onTimeUpdate);

    return () => {
      if (!player) return;
      if (player.isDisposed()) return;
      player.off('timeupdate', onTimeUpdate);
    };
  }, [isPlayerReady])

  useEffect(() => {
    if (!isPlayerReady) return;

    const player = playerRef.current;
    if (!player) return;

    const playerElement = player.el() as HTMLElement;
    const keyDownHandler = (event: KeyboardEvent) => {
      event.stopPropagation();

      if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', ' '].includes(event.key))
        event.preventDefault();

      const currentTime = player.currentTime() as number;

      switch (event.key) {
        case ' ':
          if (player.paused()) player.play(); else player.pause();
          break;
        case 'ArrowLeft':
          player.currentTime(Math.max(currentTime - 5, 0));
          break;
        case 'ArrowRight': {
          if (event.repeat) return;
          // 无论是短按还是长按，都开始播放
          if (player.paused()) player.play();
          if (longPressTimer.current) clearTimeout(longPressTimer.current);
          longPressTimer.current = setTimeout(() => {
            setOriginalPlaybackRate(player.playbackRate() ?? 1);
            player.playbackRate(2);
            setIsLongPress(true);
          }, 300);
          break;
        }
      }
    }
    const keyUpHandler = (event: KeyboardEvent) => {
      switch (event.key) {
        case 'ArrowRight':
          if (longPressTimer.current) {
            clearTimeout(longPressTimer.current);
            longPressTimer.current = null;
          }
          console.log(isLongPress);
          
          if (isLongPress === false) {
            player.currentTime(Math.min(player.currentTime() as number + 5, player.duration() as number));
          } else {
            player.playbackRate(originalPlaybackRate);
          }
          
          setIsLongPress(false);
          break;
      }
    }

    playerElement.addEventListener('keydown', keyDownHandler)
    playerElement.addEventListener('keyup', keyUpHandler)

    return () => {
      playerElement.removeEventListener('keydown', keyDownHandler)
      playerElement.removeEventListener('keyup', keyUpHandler)
      if (longPressTimer.current) clearTimeout(longPressTimer.current);
    }
  }, [isPlayerReady, isLongPress, originalPlaybackRate]);

  return (
    <div className="video-player-container">
      <div className="video-wrapper">
        <video
          ref={videoRef}
          className="video-js vjs-default-skin"
          playsInline
        />
      </div>
    </div>
  );
};

export default VideoPlayer;